<template>
  <view class="brand-edit-container">
    <form @submit.prevent="handleSubmit" class="edit-form">
      <!-- 表单内容区 -->
      <view class="form-content">
        <!-- 台桌名称 -->
        <view class="form-group">
          <text class="form-label">台桌名称 *</text>
          <input type="text" class="form-input" v-model="formData.name" placeholder="请输入台桌名称" />
          <text class="form-tip" v-if="errors.name">{{ errors.name }}</text>
        </view>
        
        <!-- 编号 -->
        <view class="form-group">
          <text class="form-label">编号 *</text>
          <input type="text" class="form-input" v-model="formData.serial_no" placeholder="请输入台桌编号" />
          <text class="form-tip" v-if="errors.serial_no">{{ errors.serial_no }}</text>
        </view>
        
        <!-- 是否虚拟 -->
        <view class="form-group">
          <text class="form-label">是否虚拟 *</text>
          <radio-group class="form-radio-group" v-model="formData.is_virtual">
            <label class="radio-label">
              <radio value="1" /> 虚拟台
            </label>
            <label class="radio-label">
              <radio value="0" /> 实际台
            </label>
          </radio-group>
        </view>
        
        <!-- 台桌类型ID -->
        <view class="form-group">
          <text class="form-label">台桌类型ID *</text>
          <picker class="form-picker" @change="handleTypeChange" :value="typeIndex" :range="typeOptions" range-key="label">
            <view class="picker-content">
              {{ typeOptions[typeIndex]?.label || '请选择台桌类型' }}
            </view>
          </picker>
          <text class="form-tip" v-if="errors.type_id">{{ errors.type_id }}</text>
        </view>
        
        <!-- 品牌ID -->
        <view class="form-group">
          <text class="form-label">品牌ID *</text>
          <input type="number" class="form-input" v-model="formData.brand_id" placeholder="请输入品牌ID" />
          <text class="form-tip" v-if="errors.brand_id">{{ errors.brand_id }}</text>
        </view>
        
        <!-- 免费类型 -->
        <view class="form-group">
          <text class="form-label">免费类型 *</text>
          <picker class="form-picker" @change="handleFreeTypeChange" :value="freeTypeIndex" :range="freeTypeOptions" range-key="label">
            <view class="picker-content">
              {{ freeTypeOptions[freeTypeIndex].label || '请选择免费类型' }}
            </view>
          </picker>
        </view>
        
        <!-- 免费时长 -->
        <view class="form-group">
          <text class="form-label">免费时长 *</text>
          <input type="number" class="form-input" v-model="formData.free_duration" placeholder="请输入免费时长" />
          <text class="form-tip" v-if="errors.free_duration">{{ errors.free_duration }}</text>
        </view>
        
        <!-- 收费类型 -->
        <view class="form-group">
          <text class="form-label">收费类型 *</text>
          <radio-group class="form-radio-group" v-model="formData.fee_type">
            <label class="radio-label">
              <radio value="hour" /> 小时
            </label>
            <label class="radio-label">
              <radio value="free" /> 不收费
            </label>
          </radio-group>
        </view>
        
        <!-- 计费时长 -->
        <view class="form-group">
          <text class="form-label">计费时长 *</text>
          <input type="number" class="form-input" v-model="formData.duration" placeholder="请输入计费时长" />
          <text class="form-tip" v-if="errors.duration">{{ errors.duration }}</text>
        </view>
        
        <!-- 价格 -->
        <view class="form-group">
          <text class="form-label">价格 *</text>
          <input type="number" class="form-input" v-model="formData.price" placeholder="请输入价格" />
          <text class="form-tip" v-if="errors.price">{{ errors.price }}</text>
        </view>
        
        <!-- VIP价格类型 -->
        <view class="form-group">
          <text class="form-label">VIP价格类型 *</text>
          <picker class="form-picker" @change="handleVipPriceTypeChange" :value="vipPriceTypeIndex" :range="vipPriceTypeOptions" range-key="label">
            <view class="picker-content">
              {{ vipPriceTypeOptions[vipPriceTypeIndex].label || '请选择VIP价格类型' }}
            </view>
          </picker>
        </view>
        
        <!-- VIP价格 -->
        <view class="form-group">
          <text class="form-label">VIP价格 *</text>
          <input type="number" class="form-input" v-model="formData.price_vip" placeholder="请输入VIP价格" />
          <text class="form-tip" v-if="errors.price_vip">{{ errors.price_vip }}</text>
        </view>
      </view>
      
      <!-- 提交区域 -->
      <view class="submit-section">
        <button type="primary" class="submit-btn" :disabled="submitting" @click="handleSubmit">{{ submitting ? '提交中...' : '提交' }}</button>
      </view>
    </form>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 表单数据
      formData: {
        id: '',
        name: '',
        serial_no: '',
        is_virtual: '1',
        type_id: '',
        brand_id: '',
        free_type: 'first',
        free_duration: '',
        fee_type: 'hour',
        duration: '',
        price: '',
        price_vip_type: 'custom',
        price_vip: ''
      },
      // 错误信息
      errors: {},
      // 提交状态
      submitting: false,
      // 选择器选项
      freeTypeOptions: [
        { label: '首次跳表', value: 'first' },
        { label: '每次调表', value: 'every' }
      ],
      vipPriceTypeOptions: [
        { label: '禁用会员价', value: 'disable' },
        { label: '自定义会员价', value: 'custom' },
        { label: '会员等级折扣计算', value: 'level' }
      ],
      // 选择器索引
      freeTypeIndex: 0,
      vipPriceTypeIndex: 0,
      typeIndex: 0,
      // 台桌类型选项
      typeOptions: []
    };
  },
  onLoad(options) {
    // 获取台桌类型列表
    this.getTableTypeList();
    
    if (options.id) {
      this.formData.id = options.id;
      this.getTableDetail(options.id);
    }
  },
  methods: {
    // 获取台桌详情（编辑模式）
    async getTableDetail(id) {
      try {
        const res = await this.$request({
          url: '/table/table/edit',
          method: 'GET',
          params: {
            ids: id
          }
        });
        
        if (res.code === 1) {
          const data = res.data;
          this.formData = {
            id: data.id,
            name: data.name,
            serial_no: data.serial_no,
            is_virtual: data.is_virtual,
            type_id: data.type_id,
            brand_id: data.brand_id,
            free_type: data.free_type || 'first',
            free_duration: data.free_duration || '',
            fee_type: data.fee_type || 'hour',
            duration: data.duration || '',
            price: data.price || '',
            price_vip_type: data.price_vip_type || 'custom',
            price_vip: data.price_vip || ''
          };
          
          // 设置选择器索引
        this.freeTypeIndex = this.freeTypeOptions.findIndex(option => option.value === this.formData.free_type);
        this.vipPriceTypeIndex = this.vipPriceTypeOptions.findIndex(option => option.value === this.formData.price_vip_type);
        // 设置台桌类型索引
        this.typeIndex = this.typeOptions.findIndex(option => option.value === Number(this.formData.type_id));
        } else {
          throw new Error(res.msg || '获取台桌详情失败');
        }
      } catch (error) {
        console.error('获取台桌详情失败:', error);
        uni.showToast({
          title: error.message || '获取台桌详情失败',
          icon: 'none'
        });
        // 返回上一页
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      }
    },
    
    // 表单验证
    validateForm() {
      this.errors = {};
      let isValid = true;
      
      if (!this.formData.name.trim()) {
        this.errors.name = '请输入台桌名称';
        isValid = false;
      }
      
      if (!this.formData.serial_no.trim()) {
        this.errors.serial_no = '请输入台桌编号';
        isValid = false;
      }
      
      if (!this.formData.type_id) {
        this.errors.type_id = '请选择台桌类型ID';
        isValid = false;
      }
      
      if (!this.formData.brand_id) {
        this.errors.brand_id = '请输入品牌ID';
        isValid = false;
      }
      
      if (!this.formData.free_duration) {
        this.errors.free_duration = '请输入免费时长';
        isValid = false;
      }
      
      if (!this.formData.duration) {
        this.errors.duration = '请输入计费时长';
        isValid = false;
      }
      
      if (!this.formData.price) {
        this.errors.price = '请输入价格';
        isValid = false;
      }
      
      if (!this.formData.price_vip) {
        this.errors.price_vip = '请输入VIP价格';
        isValid = false;
      }
      
      return isValid;
    },
    
    // 提交表单
    async handleSubmit() {
      // 验证表单
      if (!this.validateForm()) {
        return;
      }
      
      try {
        this.submitting = true;
        const url = this.formData.id ? '/table/table/edit' : '/table/table/add';
        const method = 'POST';
        const data = {
          ...this.formData
        };
        
        // 如果是编辑模式，需要保留ids字段
        if (this.formData.id) {
          data.ids = this.formData.id;
        }
        
        const res = await this.$request({
          url,
          method,
          data
        });
        
        if (res.code === 1) {
          uni.showToast({
            title: this.formData.id ? '编辑成功' : '添加成功',
            icon: 'success'
          });
          
          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          throw new Error(res.msg || (this.formData.id ? '编辑失败' : '添加失败'));
        }
      } catch (error) {
        console.error(this.formData.id ? '编辑台桌失败:' : '添加台桌失败:', error);
        uni.showToast({
          title: error.message || (this.formData.id ? '编辑失败' : '添加失败'),
          icon: 'none'
        });
      } finally {
        this.submitting = false;
      }
    },
    
    // 免费类型选择变化
    handleFreeTypeChange(e) {
      const index = e.detail.value;
      this.freeTypeIndex = index;
      this.formData.free_type = this.freeTypeOptions[index].value;
    },
    
    // VIP价格类型选择变化
      handleVipPriceTypeChange(e) {
        const index = e.detail.value;
        this.vipPriceTypeIndex = index;
        this.formData.price_vip_type = this.vipPriceTypeOptions[index].value;
      },
      
      // 获取台桌类型列表
      async getTableTypeList() {
        try {
          const res = await this.$request({
            url: '/table/type/select',
            method: 'GET'
          });
          
          if (res.code === 1) {
            this.typeOptions = res.data || [];
          } else {
            console.error('获取台桌类型列表失败:', res.msg);
          }
        } catch (error) {
          console.error('获取台桌类型列表失败:', error);
        }
      },
      
      // 台桌类型选择变化
      handleTypeChange(e) {
        const index = e.detail.value;
        this.typeIndex = index;
        this.formData.type_id = this.typeOptions[index].value;
      }
  }
};
</script>

<style scoped>
.brand-edit-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding: 20rpx;
}

/* 表单内容区 */
.form-content {
  background-color: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

/* 表单组 */
.form-group {
  margin-bottom: 30rpx;
}

.form-group:last-child {
  margin-bottom: 0;
}

/* 表单标签 */
.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

/* 表单输入框 */
.form-input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
  box-sizing: border-box;
}

/* 表单提示 */
.form-tip {
  display: block;
  font-size: 24rpx;
  color: #ff3b30;
  margin-top: 6rpx;
}

/* 单选组 */
.form-radio-group {
  display: flex;
  gap: 40rpx;
  padding: 20rpx 0;
}

.radio-label {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #333;
}

/* 选择器 */
.form-picker {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
  box-sizing: border-box;
  display: flex;
  align-items: center;
}

.picker-content {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.picker-content:after {
  content: '';
  width: 20rpx;
  height: 20rpx;
  background-image: url('/static/arrow_right.png');
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

/* 提交区域 */
.submit-section {
  margin-top: 30rpx;
  padding: 0 30rpx;
}

/* 提交按钮 */
.submit-btn {
  width: 100%;
  height: 90rpx;
  background-color: #4cd964;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.submit-btn:disabled {
  background-color: #ccc;
  color: #fff;
}
</style>